package com.xxl.job.executor.service.jobhandler;

import com.xxl.job.core.handler.annotation.XxlJob;
import com.zbowen.way.config.AppConfig;
import com.zbowen.way.utils.ResultUtils;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.config.RequestConfig;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.HttpStatus;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.util.Timeout;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.net.URLEncoder;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Component
public class DriveWayJob {

    private static Logger logger = LoggerFactory.getLogger(DriveWayJob.class);

    private static String[] fields = new String[]{"name", "duration", "distance", "restriction", "tolls", "lights", "strategy", "road", "record"};

    @Autowired
    private DataSource dataSource;


    /**
     * 1、简单任务示例（Bean模式）
     */
    @XxlJob("driveWayJobHandler")
    public void driveWayJobHandler() throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date = sdf.format(new Date());
        logger.info(date + "：执行了driveWayJobHandler");
        // 获取默认配置的 HttpClient
        CloseableHttpClient httpClient = HttpClients.createDefault();

        //  创建请求配置信息
        RequestConfig requestConfig = RequestConfig.custom()
                // 设置连接超时时间
                .setConnectTimeout(Timeout.of(3000, TimeUnit.MILLISECONDS))
                // 设置响应超时时间
                .setResponseTimeout(3000, TimeUnit.MILLISECONDS)
                // 设置从连接池获取链接的超时时间
                .setConnectionRequestTimeout(3000, TimeUnit.MILLISECONDS)
                .build();


        String[] originList = new String[]{
                "113.892136,22.669206", // 料坑新村
                "113.900743,22.674284", // 麻布新村
                "113.924247,22.674864", // 石岩新村
                "113.932263,22.67694", // 浪心村
                "113.900331,22.717035" // 玉律五区
        };

        String[] place = new String[]{"料坑新村", "麻布新村", "石岩新村", "浪心村", "玉律五区"};

        // 起点 上南大街与沙井东环路交叉口地面停车场  南方电网汽车充电站(宝安区沙井黄埔充电站工程)
        String origin1 = "113.848464,22.716398";
        // 华侨新村幼儿园
        String origin2 = "113.875715,22.571143";
        // 安乐村41区 翻身
        String origin3 = "113.900711,22.558834";
        // 南昌第二新村 固戍
        String origin4 = "113.840852,22.600392";
        // 起点经纬度 牛湾新村
        String origin5 =  "113.854718,22.580836"; //"113.854637,22.580915";

        // 终点经纬度 豪威科技大厦
        String destination = "113.952339,22.533434"; //"113.95249,22.533516";

        for (int x = 0; x < originList.length; x++) {
            String origin = originList[x];
            Map<String, String> params = new HashMap<>();
            params.put("key", AppConfig.key);
            params.put("origin", origin);
            params.put("destination", destination);
            params.put("strategy", "10");
            params.put("province", URLEncoder.encode("粤", "utf-8"));
            params.put("number", "BGB2887");
            params.put("cartype", "2");
            params.put("nosteps", "0");
            params.put("extensions", "all");

            StringBuilder sb = new StringBuilder();
            sb.append(AppConfig.url_1).append("?1=1");
            params.forEach((key, value) -> {
                sb.append("&").append(key).append("=").append(value);
            });

            // 创建 GET 请求对象
            HttpGet httpGet = new HttpGet(sb.toString());
            // 设置请求参数
            httpGet.setConfig(requestConfig);
            // 发起请求
            CloseableHttpResponse response = httpClient.execute(httpGet);
            // 获取请求状态
            int code = response.getCode();
            if (code == HttpStatus.SC_OK) {
                HttpEntity entity = response.getEntity();
                String result = EntityUtils.toString(entity);
                List<Map<String, Object>> list = ResultUtils.print2(result, place[x]);

                String sql = "INSERT INTO zbw_way_info (name, duration, distance, restriction, tolls, lights, strategy, road, record) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)";
                Connection conn = dataSource.getConnection();
                PreparedStatement pstmt = conn.prepareStatement(sql);

                for (Map<String, Object> map : list) {
                    map.put("record", date);
                    for (int i = 0; i < fields.length; i++) {
                        pstmt.setObject(i + 1, map.get(fields[i]));
                    }
                    pstmt.executeUpdate();
                }
                conn.close();
            }
        }
    }


}
